{% extends 'html/all.html' %}
{% block title %}
    我的出售
{% endblock %}
{% block head_extra %}
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <style>
        nav[aria-label="Page navigation"] {
            position: fixed;
            right: 0;
            bottom: 0;
        }

        .btn-primary1 {
            background-color: red;
            border-color: red;
            color: #fff;
            border-radius: 5px;
        }
    </style>
{% endblock %}
{% block content %}
    <div class="container my-4">
        <div class="row row-cols-1 row-cols-md-3 g-4" id="productRow">
        </div>
        <!-- 分页条 -->
        <nav aria-label="Page navigation">
            <ul class="pagination" id="pagination">
            </ul>
        </nav>
    </div>

{% endblock %}
{% block scripts %}
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            var currentPage = 1;
            var totalPages = 1;

            function truncateDescription(description) {
                if (description.length > 24) {
                    return description.substring(0, 24) + '...';
                } else {
                    return description;
                }
            }

            $('#productRow').fadeOut();  // 开始加载新页面时，隐藏当前的商品列表

            function getTotalCount() {
                $.ajax({
                    url: '/api/get_total_count',
                    type: 'GET',
                    success: function (response) {
                        if (response.status === 'success') {
                            totalPages = Math.ceil(response.data / 9);  // 假设每页显示9个商品
                            loadPage(1);
                        } else {
                            console.error('获取总数失败:', response.message);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('AJAX 请求失败:', error);
                    }
                });
            }

            function loadPage(page) {
                $.ajax({
                    url: '/api/show_my_products',
                    type: 'GET',
                    data: {
                        page: page
                    },
                    beforeSend: function () {
                        {#$('#productRow').fadeOut();  // 开始加载新页面时，隐藏当前的商品列表#}
                    },
                    success: function (response) {

                        if (response.status === 'success') {
                            var productRow = $('#productRow');
                            productRow.empty();
                            response.data.forEach((item) => {
                                var soldText = item.IsSold ? '<span class="badge bg-danger">已售</span>' : '';
                                var btnDisabled = item.IsSold ? 'disabled' : '';
                                var detailsButton = item.IsSold ? '' : '<button class="btn btn-primary" disabled>修改（暂不支持）</>';
                                var deleteButton = item.IsSold ? '' : '<button class="btn btn-primary1" data-product-id="' + item.ProductID + '">删除</button>';
                                var truncatedDescription = truncateDescription(item.Description);
                                productRow.append(
                                    `<div class="col">
                                         <div class="card">
                                             <img alt="产品图片" class="card-img-top" src="${item.ImageURL}"/>
                                             <div class="card-body">
                                                 <h5 class="card-title">${item.ProductName} ${soldText}</h5>
                                                 <h5 class="card-title">${item.Category}</h5>
                                                 <p class="card-text">${truncatedDescription}</p>
                                                 <p class="card-text">${item.Price}￥</p>
                                                 ${detailsButton}
                                                 ${deleteButton}
                                             </div>
                                         </div>
                                     </div>`
                                );
                            });

                            $('.btn-primary1').click(function () {
                                var productId = $(this).data('product-id');
                                var password = prompt('请输入密码以确认删除操作');
                                if (password) {
                                    var username = localStorage.getItem('username');
                                    $.ajax({
                                        url: '/api/delete_save',
                                        type: 'POST',
                                        data: JSON.stringify({
                                            username: username,
                                            password: password,
                                            product_id: productId
                                        }),
                                        contentType: 'application/json',
                                        success: function (response) {
                                            if (response.status === 'success') {
                                                alert('商品删除成功');
                                                location.reload();  // 刷新页面
                                            } else {
                                                alert('密码错误');
                                                console.error('删除商品失败:', response.msg);

                                            }
                                        },
                                        error: function (xhr, status, error) {
                                            console.error('AJAX 请求失败:', error);
                                        }
                                    });
                                }
                            });
                            currentPage = page;
                            updatePagination();
                            $('#productRow').fadeIn();  // 新页面的商品数据加载完成后，显示新的商品列表
                        } else {
                            console.error('加载产品失败:', response.message);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('AJAX 请求失败:', error);
                    }
                });
            }

            function updatePagination() {
                var pagination = $('#pagination');
                pagination.empty();
                var maxVisiblePages = 10;  // 最多显示的页码数量
                var startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
                var endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
                startPage = Math.max(1, endPage - maxVisiblePages + 1);  // 重新计算开始页码，以确保总是显示10个页码

                for (var i = startPage; i <= endPage; i++) {
                    var li = $('<li class="page-item"></li>');
                    if (i === currentPage) {
                        li.addClass('active');
                    }
                    var a = $('<a class="page-link" href="#"></a>').text(i);
                    a.click(function (e) {
                        e.preventDefault();
                        loadPage(parseInt($(this).text()));
                    });
                    li.append(a);
                    pagination.append(li);
                }

                if (totalPages > maxVisiblePages) {
                    var ellipsis = $('<li class="page-item disabled"><a class="page-link" href="#">...</a></li>');
                    pagination.append(ellipsis);

                    var lastPage = $('<li class="page-item"></li>');
                    var lastPageLink = $('<a class="page-link" href="#"></a>').text(totalPages);
                    lastPageLink.click(function (e) {
                        e.preventDefault();
                        loadPage(totalPages);
                    });
                    lastPage.append(lastPageLink);
                    pagination.append(lastPage);

                    var select = $('<select class="form-select"></select>');
                    for (var i = 1; i <= totalPages; i++) {
                        var option = $('<option></option>').text(i);
                        if (i === currentPage) {
                            option.attr('selected', 'selected');
                        }
                        select.append(option);
                    }
                    select.change(function () {
                        loadPage(parseInt($(this).val()));
                    });
                    pagination.append(select);
                }
            }

            getTotalCount();
        });
    </script>
{% endblock %}